from django.shortcuts import render
from rest_framework.views import APIView
from .models import *
from rest_framework.response import Response
from .serializer import *
from django.db.models import Q
from rest_framework import status


# 获取历史聊天信息 sid:sid, room:this.room, type:this.type
class ChatInfo(APIView):
    def get(self, request):
        mid = request.query_params.get('mid')
        uid = request.query_params.get("uid")
        room_id = request.query_params.get("room")
        print('room>>', room_id)
        print("mid>>", mid, "uid>>", uid)

        room = ChatRoomModel.objects.filter(room_name=room_id).first()
        room_id_id = room.id
        print('rom_id', room_id_id)

        data = []

        chat_room = ChatMessageModel.objects.filter(room_id=room_id_id).first()
        print('数据>>>', chat_room)

        user = User.objects.get(id = chat_room.user_id)
        print('user>>', user)
        merchant = Merchant.objects.get(id = chat_room.merchant_id)
        print('mid>>', merchant)

        chat_message = ChatMessageModel.objects.filter(room_id=room_id_id).all()
        print('chant', chat_message)
        for i in chat_message:
            chant_list = {
                'room':room_id,
                'username': user.account,
                'uid': user.id,
                'mid': merchant.id,
                'merchant_name': merchant.username,
                'message': i.message,
                'types': i.types
            }
            data.append(chant_list)
        return Response({
            "code": 200,
            "msg": '获取该聊天室记录成功',
            'data': data
        })


# 获取房间号
class UserXiao(APIView):
    def get(self, request):
        mid = request.query_params.get('mid')
        print('mid',mid)

        data = []
        user_info = ChatMessageModel.objects.filter(Q(merchant_id=mid)).values("user_id").distinct()
        for i in user_info:
            data.append(i)

        for j in data:
            user = User.objects.get(id = j.get("user_id"))
            j['userinfo'] = user.account

        return Response({
            'code': 200,
            'msg': "ok",
            'data': data,
            # 'chan_id': room_fan.room_name,
        })


# 查询该用户的房间号
class User_message(APIView):
    def get(self, request):
        uid = request.query_params.get('uid')
        user_img = User.objects.filter(id=uid).first()
        portrait_img = user_img.portrait_img

        # 先获取这个用户的房间号所属id
        chant = ChatMessageModel.objects.filter(user_id=uid).first()

        # 获取到这个用户的房间id
        rid_id = chant.room_id

        rid = ChatRoomModel.objects.filter(id=rid_id).first()
        print('rid>id', rid.room_name)
        return Response({
            "code": 200,
            'msg': 'ok',
            'rid': rid.room_name,
            'portrait_img': portrait_img,
        })



class Ceshi(APIView):
    def get(self,request):
        return Response(status.HTTP_200_OK)